package com.zys.background.common.config;

import org.hibernate.validator.HibernateValidator;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.SpringConstraintValidatorFactory;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

/**
 * @author zys
 * @since 2022-11-11
 */
@Configuration
@EnableAutoConfiguration
public class ValidatorConfiguration {
  @Bean
  public Validator validator(AutowireCapableBeanFactory autowireCapableBeanFactory) {
    try (
        ValidatorFactory factory = Validation.byProvider(HibernateValidator.class)
            .configure().failFast(true)
            .constraintValidatorFactory(new SpringConstraintValidatorFactory(autowireCapableBeanFactory))
            .buildValidatorFactory()
    ) {
      return factory.getValidator();
    }
  }
}
